<?php
namespace Logistics\Model;

use Common\Model\CommonModel;

class LogisticsBillModel extends CommonModel {

    /**
     * 账单列表
     */
    public function get_list($where = array(),$order = '',$from =  0,$to = 0)
    {
        $list = M("LogisticsBill")->alias("b")->field("b.*, l.logistics_name, l.manager_id, pl.logistics_name AS manager_logistics_name, u.user_nicename, u.user_phone")->where($where)
            ->join("bdt_logistics l ON l.id = b.lid","LEFT")
            ->join("bdt_logistics pl ON pl.id = l.manager_id","LEFT")
            ->join("bdt_users u ON u.id = b.uid","LEFT")
            ->order($order)
            ->limit($from, $to)
            ->select();
        return $list;
    }
    /**
     * @param $lid
     * @param $price
     * @param $model 1授信总额 2账户充值 3 会员卡充值 4开卡费 5账户充值赠送 6卡片充值赠送  7退款金额 8卡退款物流公司加钱 9二级物流公司退款
     */
    public function insert_data($lid,$price,$model){
       $add_price_model = array(1,2,5,8);
       $reduce_price_model = array(3,4,6,7,9);
        if(!in_array($model,$add_price_model) && !in_array($model,$reduce_price_model)){
            return -1;
        }
        $insert = array(
            'lid'=>$lid,
            'model'=>$model,
            'uid'=>session('ADMIN_ID'),
        );
        if(in_array($model,$reduce_price_model)){
            $price = -$price;
        }
        $insert['price'] = $price;
        $insert['create_time'] = time();
        $logistics = M("Logistics")->where(array("id"=>$lid))->find();
        
        if(empty($logistics)){
            return -2;
        }
        
        $cur_balance = round($logistics['balance']+($price),2);

        if ($logistics['id'] !== '1' && $cur_balance < 0) {
            return -3;
        }

        $insert['balance'] = $cur_balance;
        $result = $this->add($insert);

        if($result){
            M("Logistics")->where(array("id"=>$lid))->save(array("balance"=>$cur_balance));
            if ($model == 9 && $logistics['manager_id']) {

                $manager = M("Logistics")->where(array("id" => $logistics['manager_id']))->find();

                $manager_balance = round($manager['balance']-($price),2);
                M("Logistics")->where(array("id"=>$manager['id']))->save(array("balance"=>$manager_balance));
            }
            return true;
        }else{
            return false;
        }

    }
}